// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/3/3 00:26
// 文件名称 ：   user.go
// 工程名称 ：   seckill
// 开发工具 ：   GoLand
//

package repositories

import (
	"database/sql"
	"errors"
	"foreground/common"
	"foreground/datamodels"
)

type IUserRepository interface {
	Conn() (err error)
	Select(username string) (user *datamodels.User, err error)
	SelectById(id int64) (user *datamodels.User, err error)
	Insert(user *datamodels.User) (id int64, err error)
}

func NewUserManager(table string, db *sql.DB) IUserRepository {
	return &UserManager{
		table:     table,
		mysqlConn: db,
	}
}

type UserManager struct {
	table     string
	mysqlConn *sql.DB
}

func (u *UserManager) Conn() (err error) {

	if u.mysqlConn == nil {
		u.mysqlConn, err = common.NewMysqlConn()
		if err != nil {
			return err
		}
	}
	if u.table == "" {
		u.table = "user"
	}
	return
}

func (u *UserManager) Select(username string) (user *datamodels.User, err error) {
	if username == "" {
		return &datamodels.User{}, errors.New("条件不能为空!")
	}
	if err := u.Conn(); err != nil {
		return &datamodels.User{}, err
	}
	sqlStr := "SELECT * FROM user WHERE userName=?"
	stmt, err := u.mysqlConn.Prepare(sqlStr)
	if err != nil {
		return &datamodels.User{}, err
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		return &datamodels.User{}, err
	}
	defer rows.Close()
	result := common.GetResultRow(rows)
	if len(result) == 0 {
		return &datamodels.User{}, errors.New("用户不存在!")
	}
	user = new(datamodels.User)
	common.DataToStructByTagSql(result, user)
	return
}

func (u *UserManager) SelectById(id int64) (user *datamodels.User, err error) {

	if err := u.Conn(); err != nil {
		return &datamodels.User{}, err
	}
	sqlStr := "SELECT * FROM user WHERE ID=?"
	stmt, err := u.mysqlConn.Prepare(sqlStr)
	if err != nil {
		return &datamodels.User{}, err
	}
	defer stmt.Close()
	rows, err := stmt.Query(id)
	if err != nil {
		return &datamodels.User{}, err
	}
    defer rows.Close()
	result := common.GetResultRow(rows)
	if len(result) == 0 {
		return &datamodels.User{}, errors.New("用户不存在!")
	}
	user = new(datamodels.User)
	common.DataToStructByTagSql(result, user)
	return
}

func (u *UserManager) Insert(user *datamodels.User) (id int64, err error) {
	if err := u.Conn(); err != nil {
		return 0, err
	}
	sqlStr := "INSERT user SET userName=?, nickName=?, passWord=?"
	stmt, err := u.mysqlConn.Prepare(sqlStr)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	// 插入
	result, err := stmt.Exec(user.UserName, user.NickName, user.HashPassword)
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}
